package com.example.arithmeticleetcode.leetcode.nov;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @program: arithmetic-leetcode
 * @description:
 * @author: FangZhen
 * @create: 2020-11-12 09:26
 **/
public class Demo07 {

    public static void main(String[] args) {

        int[][] grid1 = {{1}, {2}, {3}, {4}, {7}, {6}, {5}};
        System.out.println(shiftGrid(grid1, 23));
        // {{6},{5},{1},{2},{3},{4},{7}}
        int[][] grid2 = {{3, 8, 1, 9}, {19, 7, 2, 5}, {4, 6, 11, 10}, {12, 0, 21, 13}};
        int[][] grid3 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        System.out.println(shiftGrid(grid2, 4)); //[[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]
        System.out.println(shiftGrid(grid3, 1)); //[[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]


    }

    public static List<List<Integer>> shiftGrid(int[][] grid, int k) {
        List<Integer> linkedList = new ArrayList<>();
        for (int i = 0, len = grid.length; i < len; i++) {
            for (int j = 0, len2 = grid[i].length; j < len2; j++) {
                linkedList.add(grid[i][j]);
            }
        }
        int size = linkedList.size();
        int lastIndex =size - k % size;
        int cycle = size / grid.length;
        linkedList.addAll(linkedList);
        int count = 0;
        List<List<Integer>> result = new ArrayList<>();
        while (count < size) {
            int tempCycle = cycle;
            List<Integer> list = new ArrayList<>();
            while (tempCycle-- > 0) {
                list.add(linkedList.get(lastIndex++));
                count++;
            }
            result.add(list);
        }
        return result;
    }
}
